<template>
	<view class="nc-address-content">
		<view class="address-list">
			<view class="address-item" v-for="(item, index) in addressList" :key="index">
				<view class="wrapper" @click="setDefault(item.id)">
					<view class="address-box">
						<view class="tag" v-if="item.is_default == 1">默认</view>
						<text class="name">{{ item.consigner }}</text>
						<text class="mobile">{{ item.mobile }}</text>
					</view>
					<view class="address-info">
						<view class="address">
							<rich-text :nodes="item.address_info"></rich-text>
							<view>{{ item.address }}</view>
						</view>
					</view>
				</view>
				<view class="address-operation">
					<text class="delete" v-if="item.is_default != 1" @click="deleteAddress(item.id, item.is_default)">【删除】</text>
					<text class="edit" @click="addAddress('edit', item.id)">【修改】</text>
				</view>
			</view>
			<uni-load-more :status="loadingType" v-if="addressList.length > 0 && pageCount > 1"></uni-load-more>
		</view>
		<button type="primary" class="add-address" @click="addAddress('add')">新增地址</button>
		<!-- #ifdef H5 -->
		<button type="primary" class="add-address" @click="getChooseAddress()" v-if="$util.isWeiXin()">一键获取地址</button>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO -->
		<button type="primary" class="add-address" @click="getChooseAddress()">一键获取地址</button>
		<!-- #endif -->
	</view>
</template>

<script>
import http from 'common/js/http.js';
import uniLoadMore from 'components/uni-load-more/uni-load-more.vue';
import { Weixin } from 'common/js/wx-jssdk.js';

export default {
	components: {
		uniLoadMore
	},
	data() {
		return {
			addressList: [],
			pageIndex: 1, //现在页数
			pageCount: 0,
			pageSize: 10, //每页加载数
			loadingType: 'loading', //加载更多
			back: '', // 返回页
			redirect: 'redirectTo', // 跳转方式
			ident: false //防止初始化时，触发上拉加载
		};
	},
	mixins: [http],
	onLoad(option) {
		if (option.back) this.back = option.back;
		if (option.redirect) this.redirect = option.redirect;
	},
	onShow() {
		this.initAddressInfo('refresh');
	},
	onHide() {
		this.addressList = [];
	},
	onReachBottom() {
		if (!this.ident) return;
		this.initAddressInfo();
	},
	methods: {
		/* 初始化地址列表 */
		initAddressInfo(type = 'add') {
			if (type === 'add') {
				if (this.loadingType === 'nomore') {
					return;
				}
				this.loadingType = 'loading';
			} else {
				this.loadingType = 'more';
			}
			if (type === 'refresh') {
				this.loadingType = 'loading';
				this.pageIndex = 1;
				this.addressList = [];
			}

			/* 加载更多 */
			this.sendRequest({
				url: 'System.Member.memberAddressList',
				data: { page_index: this.pageIndex, page_size: this.pageSize },
				success: res => {
					this.ident = true;
					let address = res.data.data;
					this.pageCount = res.data.page_count;
					if (this.pageCount == 0) {
						this.loadingType = 'nomore';
					} else {
						if (this.pageIndex < this.pageCount) {
							this.loadingType = 'more';
						} else {
							this.loadingType = 'nomore';
						}

						if (address.length > 0) {
							if (type === 'refresh') {
								this.addressList = address;
							} else {
								this.addressList = this.addressList.concat(address);
							}
							this.pageIndex++;
						}
					}
				}
			});
		},
		/* 地址跳转 */
		addAddress(type, id) {
			let data = {};
			if (this.back) data.back = this.back;
			if (this.redirect) data.redirect = this.redirect;
			if (type == 'add') {
				this.$util.redirectTo('/pages/member/address_edit/address_edit', data);
			} else {
				data.id = id;
				this.$util.redirectTo('/pages/member/address_edit/address_edit', data);
			}
		},
		/* 删除地址信息 */
		deleteAddress(id, is_default) {
			uni.showModal({
				title: '操作提示',
				content: '确定要删除该地址吗？',
				success: res => {
					if (res.confirm) {
						if (is_default == 1) {
							this.$util.showToast({ title: '默认地址，不能删除' });
							return;
						}
						this.sendRequest({
							url: 'System.Member.addressDelete',
							data: { id: id, is_default: is_default },
							success: res => {
								if (res.code == 0) {
									this.$util.showToast({ title: '删除成功' });
								} else {
									this.$util.showToast({ title: '删除失败' });
								}
								this.initAddressInfo('refresh');
							}
						});
					}
				}
			});
		},
		setDefault(id) {
			this.sendRequest({
				url: 'System.Member.modifyAddressDefault',
				data: { id },
				success: res => {
					if (res.data > 0) {
						if (this.back) {
							this.$util.redirectTo(this.back, {}, this.redirect);
						} else {
							this.initAddressInfo('refresh');
							this.$util.showToast({ title: '修改默认地址成功' });
						}
					} else {
						this.$util.showToast({ title: res.message });
					}
				}
			});
		},
		getChooseAddress() {
			// #ifdef H5
			this.sendRequest({
				url: 'System.WchatPublic.getJsApiConfig',
				data : {
					url: window.location.href
				},
				success: jsApiRes => {
					if (jsApiRes.code == 0) {
						var wxJS = new Weixin();
						wxJS.init(jsApiRes.data);
						wxJS.openAddress(res => {
							if (res.errMsg == 'openAddress:ok') {
								this.saveAddress({
									consigner: res.userName, // 收货人姓名,
									mobile: res.telNumber, // 手机号
									province: res.provinceName, // 省
									city: res.cityName, // 市
									district: res.countryName, // 县
									address: res.detailInfo, // 详细地址
									zip_code: res.postalCode // 邮编
								});
							}
						});
					}
				}
			});
			// #endif

			// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO 
			uni.chooseAddress({
				success: res => {
					if (res.errMsg == 'chooseAddress:ok') {
						this.saveAddress({
							consigner: res.userName, // 收货人姓名,
							mobile: res.telNumber, // 手机号
							province: res.provinceName, // 省
							city: res.cityName, // 市
							district: res.countyName, // 县
							address: res.detailInfo, // 详细地址
							zip_code: res.postalCode // 邮编
						});
					}
				}
			});
			// #endif
		},
		saveAddress(params) {
			this.sendRequest({
				url: 'System.Member.addWeixinAddress',
				data: params,
				success: res => {
					if (res.data > 0) {
						if (this.goback) {
							var pages = getCurrentPages();
							for (let i = pages.length - 1; i > 0; i--) {
								if (this.goback == 'payment' && pages[i].route.indexOf('pages/order/payment/payment') > -1) {
									// 返回到待付款订单
									//list->payment
									uni.navigateBack({
										delta: 1
									});
									break;
								} else if (this.goback == 'receive_prize' && pages[i].route.indexOf('pages/member/receive_prize/receive_prize') > -1) {
									// 返回到领取奖品
									//list->receive_prize
									uni.navigateBack({
										delta: 1
									});
									break;
								}
							}
						} else {
							this.initAddressInfo('refresh');
						}
					} else {
						this.$util.showToast({ title: '获取失败' });
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
.address-list {
	margin-bottom: 50rpx;
}
.address-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	min-height: 94rpx;
	background: #fff;
	border-bottom: 2rpx solid $ns-border-color-gray;
	&:first-of-type {
		border-top: 2rpx solid $ns-border-color-gray;
	}
}
.wrapper {
	display: flex;
	flex-direction: column;
	flex: 1;
	.address-box {
		display: flex;
		align-items: center;
		.tag {
			margin-right: 10rpx;
			padding: 2rpx 4rpx;
			border: 2rpx solid red;
			font-size: $uni-font-size-sm;
			line-height: 1;
			color: red;
			border-radius: 4rpx;
		}
	}
	.address {
		color: #999 !important;
		font-size: $uni-font-size-base - 2rpx;
		max-height: 80rpx;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;

		rich-text {
			display: inline-block;
			margin-right: 2px;
		}
		view{
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			max-width: 434rpx;
		}
	}
	.name {
		margin-right: 20rpx;
		font-size: $uni-font-size-base + 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 210rpx;
	}
	.mobile {
		font-size: $uni-font-size-base + 8rpx;
	}
}
.address-operation text {
	font-size: $uni-font-size-base;
	margin-left: 10rpx;
	&:first-of-type {
		margin-left: 0;
	}
}
.add-address {
	margin-top: 20rpx;
	&:last-child {
		margin-bottom: 68rpx;
	}
}
</style>
